package cn.ztf.zshop.security.admin.controller;

import cn.ztf.zshop.bean.dto.AreaVo;
import cn.ztf.zshop.bean.vo.AreaDto;
import cn.ztf.zshop.service.AreaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

/**
 * 地区管理
 * @module admin
 */
@RestController
@RequestMapping("/admin/area")
public class AreaController {
    @Autowired
    AreaService areaService;

    @GetMapping("/areaTree")
    public ResponseEntity<List<AreaVo>> list() {
        List<AreaVo> list = areaService.listArea();
        return ResponseEntity.ok(list);
    }
    @GetMapping("{areaId}")
    public ResponseEntity<AreaVo> get(@PathVariable Long areaId){
       AreaVo areaVo =  areaService.getAreaById(areaId);
       return ResponseEntity.ok(areaVo);
    }

    @PostMapping
    public ResponseEntity<Void> add(@Validated @RequestBody AreaDto areaDto){
        areaService.add(areaDto);
        return ResponseEntity.ok().build();
    }

    @PutMapping
    public ResponseEntity<?> update(@Validated({AreaDto.Update.class}) @RequestBody AreaDto areaDto){
        if (Objects.equals(areaDto.getAreaId(), areaDto.getParentId())){
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("父节点设置错误");
        }
        areaService.update(areaDto);
        return ResponseEntity.ok().build();
    }

    /**
     * 删除叶子节点数据
     * @param id
     * @return
     */
    @DeleteMapping("{id}")
    public ResponseEntity<Void> deleted(@PathVariable Long id){
        areaService.deleteAreaById(id);
        return ResponseEntity.ok().build();
    }



}
